package com.sskj.mine.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.SuperTextView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.AppVersionBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.CopyUtil;
import com.sskj.lib.util.HideUtil;
import com.sskj.lib.util.TipUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.InviteStatusBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.MineFragmentPresenter;
import com.sskj.mine.ui.activity.SettingActivity;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/05/01
 */
@Route(path = RConfig.MINE_FRAGMENT_MAIN)
public class MineFragment extends BaseFragment<MineFragmentPresenter> {


    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.tvAccount)
    TextView tvAccount;

    @BindView(R2.id.tvUSDT)
    TextView tvUSDT;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.tvUID)
    TextView tvUID;


    @BindView(R2.id.menu_security_center)
    SuperTextView menuSecurityCenter;
    @BindView(R2.id.menu_notice)
    SuperTextView menuNotice;
    @BindView(R2.id.menu_about_us)
    SuperTextView menuAboutUs;
    @BindView(R2.id.menu_feedback)
    SuperTextView menuFeedback;
    @BindView(R2.id.menu_help_center)
    SuperTextView menuHelpCenter;
    @BindView(R2.id.menu_contact_us)
    SuperTextView menuContactUs;
    @BindView(R2.id.menu_system)
    SuperTextView menuSystem;
    @BindView(R2.id.menu_address_manage)
    SuperTextView menuAddressMange;
    @BindView(R2.id.menu_setting)
    SuperTextView menuSetting;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.llControl)
    LinearLayout llControl;
    @BindView(R2.id.cbSee)
    CheckBox cbSee;
    @BindView(R2.id.llRecharge)
    LinearLayout llRecharge;
    @BindView(R2.id.llWithdraw)
    LinearLayout llWithdraw;
    @BindView(R2.id.llRecord)
    LinearLayout llRecord;
    @BindView(R2.id.llInvite)
    LinearLayout llInvite;
    @BindView(R2.id.llAsset)
    LinearLayout llAsset;
    @BindView(R2.id.tvFrozen)
    TextView tvFrozen;
    private UserData userData;
    private boolean isSee = true;
    private Disposable refreshDispo;

    @Override
    public int getLayoutId() {
        return R.layout.mine_fragment_mine;
    }

    @Override
    public MineFragmentPresenter getPresenter() {
        return new MineFragmentPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                DisposUtil.close(refreshDispo);
                refreshDispo = Flowable.timer(2, TimeUnit.SECONDS)
                        .compose(RxSchedulersHelper.transformer())
                        .subscribe(aLong -> {
                            refreshView.setRefreshing(false);
                        });
                userViewModel.update();
            }
        });
        updateUserTitle();


    }

    @Override
    public void initData() {
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.getFrozen();

            } else {
                userData = null;
            }
            updateUserTitle();
        });
        mPresenter.getInvite();
    }

    @Override
    protected void initEvent() {


        ClickUtil.click(tvAccount, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
        });

        ClickUtil.click(llInvite, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.INVITE_MENU).navigation();
        });
        ClickUtil.click(llRecord, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.TIBI_RECORD).navigation();

        });

        ClickUtil.click(menuFeedback, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.MINE_FEEDBACK).navigation();
        });

        ClickUtil.click(menuSetting, () -> {
            SettingActivity.start(getContext());
        });

        ClickUtil.click(llRecharge, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.TIBI_RECHARGE).navigation();
        });


        ClickUtil.click(llWithdraw, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }

            if (!AppCircleCheckUtil.checkHighAuth(getActivity(), userData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.TIBI_WITHDRAW).navigation();
        });


        ClickUtil.click(menuHelpCenter, () -> {
            ARouter.getInstance().build(RConfig.MINE_HELP_CENTER).navigation();
        });


        ClickUtil.click(menuSecurityCenter, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
        });
        ClickUtil.click(menuNotice, () -> {
            ARouter.getInstance().build(RConfig.HANG_GONGGAO_LIST).navigation();
        });

        ClickUtil.click(menuAboutUs, () -> {
            ARouter.getInstance().build(RConfig.HANG_GUIDE_WEB).withBoolean(Constans.IS_ABOUT_US, true).navigation();
        });
        ClickUtil.click(menuAddressMange, () -> {
            if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.TIBI_ADDRESS_LIST).navigation();
        });

        ClickUtil.click(menuContactUs, () -> {
            mPresenter.getContract();
//            ToastUtil.showShort(getString(R.string.mine_mineFragment1));
//            ARouter.getInstance().build(RConfig.HANG_GUIDE_WEB).withBoolean(Constans.IS_GUEST, true).navigation();
//            ARouter.getInstance().build(RConfig.MINE_CONTACT_US).navigation();
        });

        ClickUtil.click(menuSystem, () -> {
            mPresenter.checkVersion();
        });
    }

    public void updateUserTitle() {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        if (userData != null) {
            llAsset.setVisibility(View.VISIBLE);
            llControl.setVisibility(View.VISIBLE);
//            if (TextUtils.isEmpty(userData.getTel())){
//                tvAccount.setText( HideUtil.getEmialAddress(userData.getEmail()));
//            }else {
//                tvAccount.setText( HideUtil.getPhoneHide(userData.getTel()));
//            }
            tvAccount.setText(SPUtil.get(SPConfig.USER_ACCOUNT, "").contains("@") ? HideUtil.getEmialAddress(SPUtil.get(SPConfig.USER_ACCOUNT, "")) : HideUtil.getPhoneHide(SPUtil.get(SPConfig.USER_ACCOUNT, "")));
            tvUSDT.setText(isSee ? (userData.getFound() != null ? userData.getFound().getUsdtTotal() : "----") : "****");

            tvUID.setText("UID:" + userData.getUserUid());
            if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
                coolRefreshView.setRefreshing(false);
            }
            cbSee.setOnCheckedChangeListener((buttonView, isChecked) -> {
                isSee = isChecked;
                if (userData == null) {
                    return;
                }
                tvUSDT.setText(isSee ? (userData.getFound() != null ? userData.getFound().getUsdtTotal() : "----") : "****");
            });
            tvRMB.setText(String.format("≈%sCNY", userData.getFound().getCnyTotal()));
        } else {
            tvUID.setText("");
            llAsset.setVisibility(View.GONE);
            llControl.setVisibility(View.GONE);
            tvAccount.setText(getString(R.string.minemineFragment1));
            tvUSDT.setText("--");
            tvRMB.setText("--");

        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(refreshDispo);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (userViewModel != null) {
            userViewModel.update();
            mPresenter.getInvite();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (userViewModel != null) {
                userViewModel.update();
                mPresenter.getInvite();
            }
        }
    }


    public void showEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return;
        }
        TipUtil.getSureTip(getActivity(), ""/*App.INSTANCE.getString(R.string.minemineFragment2)*/, email, App.INSTANCE.getString(R.string.minemineFragment3), () -> {
            CopyUtil.copy(email);
        });

    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
//        LiveDataBus.get().with(RxBusCode.SHOW_VERSION)
//                .postValue(versionBean);
        LiveEventBus
                .get("version", AppVersionBean.class).post(versionBean);

    }


    public void updateInvite(InviteStatusBean inviteStatusBean) {
        if (inviteStatusBean.getValue().equals("1")) {
            llInvite.setVisibility(View.VISIBLE);
        } else {
            llInvite.setVisibility(View.GONE);

        }

    }

    public void updateFrozen(String frostFund) {
        tvFrozen.setText(frostFund);
    }
}
